package isquirrel;

import java.util.Iterator;
import java.util.List;

import isquirrel.beans.Property;
import isquirrel.beans.User;
import isquirrel.beans.UserInterest;
import isquirrel.beans.UserLike;
import isquirrel.recommender.DynamicRecommender;
import isquirrel.semantic.DBpedia;
import isquirrel.util.HibernateUtil;

public class LikeWorker extends Thread{
	
	private volatile boolean _threadstop = false;
	
	@Override
	public void run() {
		
		QueuePool.addQueue("like", UserInterest.class);
		DBpedia dbPedia = new DBpedia();
		
		int sleeptime = 20;
		while (!_threadstop){
			
			UserLike ul  = null;
			try{
				if (QueuePool.getQueue("like").size() > 0){
					ul = (UserLike) QueuePool.getQueue("like").remove();
				}
			}
			catch(Exception e){	
				ul = null;
			}
			
			if (ul != null){
				
				sleeptime = 40;
				
				HibernateUtil.beginTransaction();
				List<Property> props = dbPedia.getPageInformation(ul.getLikedURL());
				Iterator<Property> iter = props.iterator();
				User u = UserManager.getUser(ul.getUsername());
				
				while (iter.hasNext()){
					u.addProperty(iter.next());
				}

				HibernateUtil.getSession().flush();
//				System.out.println("Adding dynamic recommendations..");

				DynamicRecommender.updateRecommendations(u);
				HibernateUtil.commit();
				
			}
			else {
				sleeptime += 4;
				if (sleeptime > 200){
					sleeptime = 200;
				}
			}
			
			try {
				Thread.sleep(sleeptime);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	
	}
	
	public void stopThread(){
		_threadstop = true;
	}
	
	
}
